﻿using DevExpress.ExpressApp.DC;
using System.Collections.ObjectModel;
using System.Xml.Linq;

namespace EasyXaf.EntityDesigner.Editors.DetailViewEditors.Models;

/// <summary>
/// 选项卡
/// </summary>
[DomainComponent]
[XafDisplayName("选项卡")]
public class Tabs : Component
{
    private int _activeTabIndex;

    /// <summary>
    /// 活动选项卡索引
    /// </summary>
    public int ActiveTabIndex
    {
        get => _activeTabIndex = Math.Min(Math.Max(_activeTabIndex, 0), Panels.Count - 1);
        set => _activeTabIndex = value;
    }

    public ObservableCollection<Panel> Panels { get; }

    public Tabs(Component parent, LayoutDesigner layoutDesigner)
        : base(parent, layoutDesigner)
    {
        Panels = [new Panel(this, layoutDesigner) { Caption = "选项卡", LayoutDirection = LayoutDirection.Vertical, IsRoot = true }];
    }

    public Component FindComponent(Guid componentId)
    {
        Component component = Panels.FirstOrDefault(p => p.Oid == componentId);
        if (component == null)
        {
            foreach (var panel in Panels)
            {
                component = panel.FindComponent(componentId);
                if (component != null)
                {
                    break;
                }
            }
        }
        return component;
    }

    public override void WriteToXml(XElement element)
    {
        base.WriteToXml(element);

        foreach (var panel in Panels)
        {
            var panelElement = panel.CreateXElement();
            panel.WriteToXml(panelElement);
            panel.IsRoot = true;
            element.Add(panelElement);
        }
    }

    public override void ReadFromXml(XElement element)
    {
        base.ReadFromXml(element);

        Panels.Clear();

        var children = element.Elements();
        foreach (var child in children)
        {
            var elementName = child.Name.LocalName;
            if (elementName == "h" || elementName == "v")
            {
                var panel = new Panel(this, LayoutDesigner);
                panel.ReadFromXml(child);
                panel.IsRoot = true;
                Panels.Add(panel);
            }
        }
    }

    public override XElement CreateXElement()
    {
        return new XElement("t");
    }
}
